package org.softmed.rest.server.defaults.boot;

import groovy.lang.Binding;
import groovy.lang.GroovyClassLoader;
import groovy.lang.GroovyShell;
import groovy.util.GroovyScriptEngine;

import java.io.File;
import java.util.List;
import java.util.Map;

import org.softmed.filehandling.FileUtil;
import org.softmed.rest.server.core.restlet.RESTServer;

import com.google.inject.Inject;

public class BootupScriptReaderUtil {

	@Inject
	GroovyScriptEngine groovyScriptEngine;

	@Inject
	GroovyClassLoader groovyClassLoader;

	FileUtil util = new FileUtil();

	public void runBootupScripts(List<File> scripts,
			Map<String, Object> options, RESTServer server) throws Throwable {

		//Class.forName("twitterloader.DateConverter");
		
		if (scripts == null) {
			System.err.println("No Bottup Scripts to run");
			return;
		}

		for (File file : scripts) {
			try {
				runScript(file, options, server);
			} catch (Throwable t) {
				t.printStackTrace();
			}
		}

		// System.out.println("bootup scripts run");
	}

	private void runScript(File file, Map<String, Object> options,
			RESTServer server) throws Throwable {
		String script = util.readFromFile(file);

		Binding binding = new Binding();
		binding.setVariable("options", options);
		binding.setVariable("server", server);
//		System.out.println("GROOVY CLASS LOADER: " + groovyClassLoader);
		GroovyShell shell = new GroovyShell( groovyClassLoader, binding);

		try {
			shell.evaluate(script);
		} catch (Throwable t) {
			System.err.println("Error evaluating script " + file.getName());
			System.err.println("Groovy Script File Path : "
					+ file.getCanonicalPath());
			throw t;
		}

	}

}
